package org.tio.sitexxx.web.server.controller.minip;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.Coupon;
import org.tio.sitexxx.service.model.main.Member;
import org.tio.sitexxx.service.model.main.Payment;
import org.tio.sitexxx.service.model.main.Question;
import org.tio.sitexxx.service.service.qj.CouponService;
import org.tio.sitexxx.service.service.qj.MemberService;
import org.tio.sitexxx.service.service.qj.PaymentService;
import org.tio.sitexxx.service.service.qj.QuestionService;
import org.tio.sitexxx.service.vo.Const;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestPath(value = "/question")
public class QuestionController {
    private static Logger log = LoggerFactory.getLogger(QuestionController.class);
    /**
     * 返回所有已支付过的问题
     * @param openid
     * @return
     */
    @RequestPath(value ="/list")
    public List<Question> list(String openid) {
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);
        query.put("memberId", Member.getId());
        return QuestionService.me.getQuestionsByMember(query);
    }

    /**
     * 用户提问插入数据库，此逻辑在订单初始化之前，是不合理的，
     * 问题status字段含义  1表示未回答0表示已回答  2表示正在回答(还未实现)
     * @param request
     * @return
     */
    @RequestPath(value = "/upsert")
    public Map<String, Object> upsert(HttpRequest request) {
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        String openid = (String)body.get("openid");
        Integer status = 1;
        String consultant = (String)body.get("consultant");
        String video = (String)body.get("video");
        String clothing_price_range = (String)body.get("clothing_price_range");
        String content = (String)body.get("content");
        String []images=new String[] {"","",""};
        JSONArray imgageUrl=JSON.parseArray(JSON.toJSONString(body.get("imageurl")));
        System.out.println("image:"+JSON.toJSONString(imgageUrl));
        for(int i=0;i<=imgageUrl.size()-1&&imgageUrl.size()<=3;i++){
//            image1=imgageUrl[i];
            images[i]=imgageUrl.getString(i);
        }
        String occasion = (String)body.get("occasion");
        String temperature = (String)body.get("temperature");
//        Integer type = Integer.valueOf((String)body.get("type"));这个type数据库里可以看到有1或者2  1为普通问题，2为专属问题就是指定哪个顾问回答 但这里写死为1

        Map<String, Object> query = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        query.put("openid", openid);
        Member Member = MemberService.me.getMember(query);
        Date date=new Date();
        Record question=new Record().set("memberId",Member.getId()).set("consultant",consultant).set("is_public",0).set("paid",0)
                .set("can_you_answer",0).set("video",video).set("status",status).set("clothing_price_range",clothing_price_range)
                .set("content",content).set("image1",images[0]).set("image2",images[1]).set("image3",images[2]).set("occasion",occasion)
                .set("temperature",temperature).set("type",1).set("createdAt",date).set("updatedAt",date);
        Db.use(Const.Db.TIO_SITE_MAIN).save("question","id",question);
        resultMap.put("id", question.get("id"));
        return resultMap;
    }

    /**
     * 初始化订单
     * @param request
     * @return
     */
    @RequestPath(value = "/pay/init")
    public Map<String, Object> pay_init(HttpRequest request) {
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        //优惠卷id
        Integer coupon_id = (Integer)(body.get("coupon_id"));
        //问题id
        Integer question_id = Integer.valueOf(body.get("question_id").toString());
        System.out.println("question id:"+question_id);
        //需付金额
        Integer amount_payable = Integer.valueOf(body.get("amount_payable").toString());
        //是否公开
        int is_public = Integer.valueOf((String) body.get("is_public"));
        boolean ispublic =(is_public==1);//1为公开0为不公开  默认公开
        String openid = (String) body.get("openid");

        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        System.out.println(openid);
        Member Member = MemberService.me.getMember(query);
        query.put("id", question_id);
        Question Question = QuestionService.me.getQuestion(query);
//        Question.setIsPublic(is_public);
        QuestionService.me.update_isPublic(Question.getId(),ispublic);
        Integer value;
        Coupon Coupon;
        if (coupon_id != null) {
            query.put("id", coupon_id);
            Coupon = CouponService.me.getCouponById(coupon_id);
            value = Coupon == null ? 0 : Coupon.getValue();
        } else {
            value = 0;
        }


        int delta = amount_payable - value;
        int discount_amount = (delta > 0) ? value : amount_payable;
        //实付金额
        int pay_amount = (delta > 0) ? delta : 0;

        String order_id = "q-" + System.currentTimeMillis() + "-" + Question.getId() + "-" + (value > 0 ? coupon_id : -1);
            Date date=new Date();
            Record payment=new Record().set("orderid",order_id).set("pay_amount",pay_amount).set("amount",amount_payable)
                    .set("type","question").set("createdAt",date).set("questionId",question_id)
                    .set("updatedAt",date).set("is_paid",0).set("memberId",Member.getId()).set("coupon",coupon_id);
            Db.save("payment","id",payment);

        int payment_id=Integer.valueOf(payment.get("id").toString());

        return PayParameters.payParameters.Parameters(openid,pay_amount,order_id,payment_id,log,"question",discount_amount);

    }

    @RequestPath(value ="/chargePay/submit")
    //余额支付成功
    public Map<String, Object> chargePay_submit(HttpRequest request) {
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        String openid = (String) body.get("openid");
        Integer question_id = Integer.valueOf( body.get("question_id").toString());
        Integer payment_id = Integer.valueOf( body.get("payment_id").toString());
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> query = new HashMap<>();
        query.put("openid", openid);
        System.out.println(openid);
        Member Member = MemberService.me.getMember(query);

        query.put("id", question_id);
        Question Question = QuestionService.me.getQuestion(query);
        System.out.println("questionid:"+question_id);
        System.out.println("question:"+JSON.toJSONString(Question));

        query.put("id", payment_id);
        Payment Payment = PaymentService.me.getPayment(query);
        System.out.println("Payment:"+JSON.toJSONString(Payment));
        System.out.println("paymentId:"+payment_id);
        if (Question == null) {
            resultMap.put("ok", 1);
            resultMap.put("msg", "支付失败");
            return resultMap;
        }
        if (Payment == null) {
            resultMap.put("ok", 1);
            resultMap.put("msg", "支付失败");
            return resultMap;
        }
        if (Member.getBalance() == null || Member.getBalance() < Payment.getPayAmount()) {
            resultMap.put("ok", 1);
            resultMap.put("msg", "支付失败");
            return resultMap;
        }


        Coupon Coupon;
        if (Payment.getCoupon() != null) {
            query.put("id", Payment.getCoupon());
            Coupon = CouponService.me.getCouponById(Payment.getCoupon());
        } else {
            Coupon = null;
        }

        if (Coupon != null) {
            Coupon.setStatus((short)3);
            CouponService.me.update(Coupon);
        }

        Member.setBalance(Member.getBalance() - Payment.getPayAmount());
        MemberService.me.update(Member);

        Payment.setIsPaid(true);
        PaymentService.me.update(Payment);

        Question.setPaid(true);
        QuestionService.me.update_is_paid(Question.getId(),true);

        return resultMap;
    }

    @RequestPath(value ="/pay/submit")
    //现金支付成功
    public Map<String, Object> pay_submit(HttpRequest request) {
        Map<String, Object> body = JSON.parseObject(request.getBodyString());
        Integer question_id = Integer.valueOf( body.get("question_id").toString());
        Integer payment_id = Integer.valueOf( body.get("payment_id").toString());
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> query = new HashMap<>();
        query.put("id", question_id);
        Question Question = QuestionService.me.getQuestion(query);

        query.put("id", payment_id);
        Payment Payment = PaymentService.me.getPayment(query);

        Coupon Coupon;
        if (Payment.getCoupon() != null) {
            query.put("id", Payment.getCoupon());
            Coupon = CouponService.me.getCouponById(Payment.getCoupon());
        } else {
            Coupon = null;
        }

        if (Coupon != null) {
            Coupon.setStatus((short)3);
            CouponService.me.update(Coupon);
        }

        if (Payment == null) {
            resultMap.put("ok", 1);
            return resultMap;
        }

        Payment.setIsPaid(true);
        PaymentService.me.update(Payment);

        Question.setPaid(true);
        QuestionService.me.update_is_paid(Question.getId(),true);

        resultMap.put("ok", 0);
        return resultMap;

    }

}
